#include<stdio.h> 
#include<stdlib.h>
#include<string.h>

//s表的长度取256
#define SBOX_SIZE 256

unsigned char sbox[SBOX_SIZE]={0};

//初始化s表
static void init_sbox(unsigned char*key, int key_len){
	unsigned int i,j,k;
	int tmp;
	
	for(i=0;i<SBOX_SIZE;i++){
		sbox[i]=i;
	}
	
	j=k=0;
	for(i=0;i<SBOX_SIZE;i++){
		tmp=sbox[i];
		j=(j+tmp+key[k])%SBOX_SIZE;
		sbox[i]=sbox[j];
		sbox[j]=tmp;
		if( ++k>=key_len ) k=0;
	}
}

//加解密函数
int rc4_crypt(unsigned char*key,int key_len, unsigned char*data, int data_len)
{
	int i,j,k,R,tmp;
	if(!key || !key_len || !data || !data_len) return -1;
	init_sbox(key, key_len);
	
	j=k=0;	
	for(i=0;i<data_len;i++){
		j=(j+1)%SBOX_SIZE;
		k=(k+sbox[j])%SBOX_SIZE;
		
		tmp=sbox[j];
		sbox[j]=sbox[k];
		sbox[k]=tmp;
		
		R=sbox[(sbox[j]+sbox[k])%SBOX_SIZE];
		
		data[i]^=R;
	}	
    return 0;
}

int rc4_demo()  //rc4_demo
{
	unsigned char data[100]={0};
    unsigned char *str = "rc4 encrypt testing.";
    unsigned char *key = "1238521asccas";
    sprintf(data, "%s", str);
	rc4_crypt(key ,strlen(key), data, strlen(data));
	printf("enc: %s\n",data);
	rc4_crypt(key ,strlen(key), data, strlen(data));
	printf("dec: %s\n",data);
	return 0;
}
